import { ElLoading,ElNotification } from 'element-plus';
import { useAdminInfo } from '../store/adminInfo'
import router from '../router/index'
const adminInfo = useAdminInfo()
const loadingInstance = {
    target: null,
    count: 0,
}

/**
 * 关闭Loading层实例
 */
function closeLoading(options) {
    if (options.loading) {
        if (loadingInstance.count > 0) loadingInstance.count--
        if (loadingInstance.count === 0) {
            loadingInstance.target.close()
            loadingInstance.target = null
        }
    }
}

export async function doPyViewInvoke (method,data,options,loading){
    options = Object.assign(
        {
            loading: false, // 是否开启loading层效果, 默认为false
            showErrorMessage: true, // 是否开启接口错误信息展示,默认为true
            showCodeMessage: false, // 是否开启code不为1时的信息提示, 默认为true
            showSuccessMessage: false, // 是否开启code为1时的信息提示, 默认为false
        },
        options
    )
    if (options.loading) {
        loadingInstance.count++
        if (loadingInstance.count === 1) {
            loadingInstance.target = ElLoading.service(loading)
        }
    }
    const token = adminInfo.getToken()
    return await window.pywebview.api.do_something(method,data,token).then(
        (message) => {
            let res = message;
            if (options.showErrorMessage && res.code != 200) {
                if (response.data.code == 409) {
                    //这里需要刷新token逻辑暂时加长token有效期无需刷新
                    router.push({ name: 'login' })
                }
                if(response.data.code == 401){
                    router.push({ name: 'login' })
                }
                if (options.showErrorMessage) {
                    ElNotification({
                        type: 'error',
                        message: response.data.msg,
                    })
                }
            }
            if(options.showSuccessMessage && res.code == 200){
                ElNotification({
                    type: 'success',
                    message: res.msg,
                })
            }
            closeLoading(options)
            return res;
        }
    ).catch(
        (error) => {
            closeLoading(options)
            if(options.showErrorMessage){
                ElNotification({
                    type: 'error',
                    message: error,
                })
            }
            return error
        }
    )
}

